package com.tedu.weibo.controller;

import com.tedu.weibo.mapper.UserMapper;
import com.tedu.weibo.pojo.dto.UserLoginDTO;
import com.tedu.weibo.pojo.dto.UserRegDTO;
import com.tedu.weibo.pojo.entity.User;
import com.tedu.weibo.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    /**
     * 用户注册
     *
     * @param userRegDTO
     * @return 注册成功:1
     * 账号已存在:2
     */
    @PostMapping("/reg")
    public int reg(@RequestBody UserRegDTO userRegDTO) {
        System.out.println(userRegDTO);
        /**
         * 判断用户名是否已存在，先调用userRegDTO的.getUsername()获取用户名，
         * 再使用userMapper的.selectByUsername()查询是否存在
         */
        if (userMapper.selectByUsername(userRegDTO.getUsername()) != null) {
            return 2;
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return 1;
    }

    /**
     * 用户登录
     *
     * @param userLoginDTO
     * @param session
     * @return
     */
    @PostMapping("/login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, HttpSession session) {
        System.out.println(userLoginDTO);
        User user = userMapper.selectByUsername(userLoginDTO.getUsername());
        if (user != null) {
            if (!user.getPassword().equals(userLoginDTO.getPassword())) {
                return 2;
            } else {
                session.setAttribute("user", user);
                return 1;
            }
        } else {
            return 3;
        }
    }


    /**
     * 获取当前用户登录信息，临时自动登录
     *
     * @param session
     * @return session中保存的有user: UserVO
     * ,null:未登录
     */
    @GetMapping("/currentUser")
    public UserVO currentUser(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return null;
        } else {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }
    }

    /**
     * 退出登录
     * @param session
     */
    @GetMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }


}
